package com.zkl.common.web.app.base;

import com.baomidou.mybatisplus.extension.activerecord.Model;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Description 基础实体
 * @Date 2019/3/22 9:25
 * @Created by gongxz
 */
public class BaseModel<T> extends Model<BaseModel<T>> {

	/**
	 * 获取指定值
	 * @param name 属性名
	 * @return
	 */
	public <T> T get(String name) {
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field field : fields) {
			if (name.equals(field.getName())) {
				String firstLetter = name.substring(0, 1).toUpperCase();
				String getter = "get" + firstLetter + name.substring(1);
				try {
					Method method = this.getClass().getMethod(getter);
					return (T) method.invoke(this);
				} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
					e.printStackTrace();
				}
				return null;
			}
		}
		return null;
	}

	/**
	 * 给指定值赋值
	 * @param name 属性名
	 * @return
	 */
	public <T> void set(String name,T t) {
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field field : fields) {
			if (name.equals(field.getName())) {
				String firstLetter = name.substring(0, 1).toUpperCase();
				String setter = "set" + firstLetter + name.substring(1);
				try {
					Method method = this.getClass().getMethod(setter, t.getClass());
					method.invoke(this, t);
				} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
